<template>
	<button open-type="chooseAvatar" @chooseavatar="bindchooseavatar" @click="uploadAvatarImg" class="box" :class="{'showBorder':border}"  :style="{width,height,lineHeight:height}">
		<cloud-image v-if="avatar_file" :src="avatarHandler(userInfo)" :width="width" :height="height"></cloud-image>
		<uni-icons v-else :style="{width,height,lineHeight:height}" class="chooseAvatar" type="plusempty" size="30"
			color="#dddddd"></uni-icons>
	</button>
</template>

<script>
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	
	import {
		avatarHandler
	} from '@/utils/common.js'
	/**
	* uni-id-pages-avatar 
	* @description 用户头像组件
	* @property {String} width	图片的宽，默认为：50px
	* @property {String} height	图片的高，默认为：50px
	*/
	export default {
		data() {
			return {
				isPC: false
			}
		},
		props: {
			//头像图片宽
			width: {
				type: String,
				default () {
					return "50px"
				}
			},
			//头像图片高
			height: {
				type: String,
				default () {
					return "50px"
				}
			},
			border:{
				type: Boolean,
				default () {
					return false
				}
			}
		},
		async mounted() {
			// #ifdef H5
			this.isPC = !['ios', 'android'].includes(uni.getSystemInfoSync().platform);
			// #endif
		},
		computed: {
			hasLogin() {
				return store.hasLogin
			},
			userInfo() {
				return store.userInfo
			},
			avatar_file() {
				return store.userInfo.avatar_file
			}
		},
		methods: {
			avatarHandler(userinfo){
				return avatarHandler(userinfo)
			},
			setAvatarFile(avatar_file) {
				// 使用 clientDB 提交数据
				mutations.updateUserInfo({avatar_file})
			},
			/**
			 * uploadAvatar() 上传头像并增加一条审核信息
			 * filePath 本地文件路径
			 * cloudPath 云端文件路径
			*/
			async uploadAvatar(filePath, cloudPath){
				uni.showLoading({
					title: "上传中",
					mask: true
				});
				try{
					let {
						fileID
					} = await uniCloud.uploadFile({
						filePath,
						cloudPath,
						fileType: "image"
					});
					// 新增修改头像申请
					const db = uniCloud.database()
					const avtckdb =  db.collection('wallpaper-avatar-check')
					const res = await avtckdb.where(`"fromUserId == '${this.userInfo._id}'"`).get()
					
					if(res.result.data.length != 0){
						// 覆盖请求
						avtckdb.where(`"fromUserId == '${this.userInfo._id}'"`).update({
							newAvatarUrl: fileID
						})
						// 删除之前的图片
						uniCloud.callFunction({
							name: 'my-deleteFiles',
							data: {
								fileList: [res.result.data[0].newAvatarUrl] // 替换为你要删除的文件 ID
							},
							success: (res) => {
								// console.log('删除结果:', res.result);
							},
							fail: (error) => {
								// console.error(error);
							}
						});
					}else{
						// 新增请求
						avtckdb.add({
							newAvatarUrl: fileID
						})
					}
					uni.showToast({
						title: "头像已上传，请耐心等待审核",
						icon: "none"
					})
					
					// 审核通过才进行用户信息修改
					// avatar_file.url = fileID
					// this.setAvatarFile(avatar_file)
				}catch(e){
					//TODO handle the exception
					uni.showModal({
						title:	"提示",
						content: "头像上传失败，请检查网络"
					})
				}finally{
					uni.hideLoading()
				}
			},
			async bindchooseavatar(res){
				let avatarUrl = res.detail.avatarUrl
				let avatar_file = {
					extname: avatarUrl.split('.')[avatarUrl.split('.').length - 1],
					name:'',
					url:''
				}
				//上传到服务器
				let cloudPath = this.userInfo._id + '' + Date.now()
				this.uploadAvatar(avatarUrl, cloudPath)
				// avatar_file.name = cloudPath
				// try{
				// 	uni.showLoading({
				// 		title: "更新中",
				// 		mask: true
				// 	});
				// 	let {
				// 		fileID
				// 	} = await uniCloud.uploadFile({
				// 		filePath:avatarUrl,
				// 		cloudPath,
				// 		fileType: "image"
				// 	});
				// 	avatar_file.url = fileID
				// 	uni.hideLoading()
				// }catch(e){
				// 	console.error(e);
				// }
				// console.log('avatar_file',avatar_file);
				// this.setAvatarFile(avatar_file)
			},
			uploadAvatarImg(res) {
				// #ifdef MP-WEIXIN
				return false // 微信小程序走 bindchooseavatar方法
				// #endif
				
				// #ifndef MP-WEIXIN
				if(!this.hasLogin){
					return uni.navigateTo({
						url:'/pages/login/login/login-withoutpwd'
					})
				}
				const crop = {
					quality: 100,
					width: 600,
					height: 600,
					resize: true
				};
				uni.chooseImage({
					count: 1,
					crop,
					success: async (res) => {
						let tempFile = res.tempFiles[0],
							avatar_file = {
								// #ifdef H5
								extname: tempFile.name.split('.')[tempFile.name.split('.').length - 1],
								// #endif
								// #ifndef H5
								extname: tempFile.path.split('.')[tempFile.path.split('.').length - 1]
								// #endif
							},
							filePath = res.tempFilePaths[0]
							const imageName = res.tempFiles[0].name
							// 后缀
							const extname = imageName.substring(imageName.lastIndexOf('.'))
							
						//非app端剪裁头像，app端用内置的原生裁剪
						// #ifdef H5
						if (!this.isPC) {
							filePath = await new Promise((callback) => {
								uni.navigateTo({
									url: '/pages/login/userinfo/cropImage/cropImage?path=' +
										filePath + `&options=${JSON.stringify(crop)}`,
									animationType: "fade-in",
									events: {
										success: url => {
											callback(url)
										}
									},
									complete(e) {
										console.log(e);
									}
								});
							})
						}
						// #endif
						let cloudPath = 'avatar/' + this.userInfo._id + '' + Date.now() + extname
						avatar_file.name = cloudPath
						
						// 上传审核
						this.uploadAvatar(filePath, cloudPath)
						// 以下为默认不审核,上传后直接更新
						// uni.showLoading({
						// 	title: "更新中",
						// 	mask: true
						// });
						// let {
						// 	fileID
						// } = await uniCloud.uploadFile({
						// 	filePath,
						// 	cloudPath,
						// 	fileType: "image"
						// });
						// avatar_file.url = fileID
						// uni.hideLoading()
						// this.setAvatarFile(avatar_file)
					}
				})
				// #endif
			}
		}
	}
</script>

<style >
	/* #ifndef APP-NVUE */
	.box{
		overflow: hidden;
	}
	/* #endif */
	.box{
		padding: 0;
	}
	
	.chooseAvatar {
		/* #ifndef APP-NVUE */
		display: inline-block;
		box-sizing: border-box;
		/* #endif */
		border-radius: 10px;
		text-align: center;
		padding: 1px;
	}
	.showBorder{
		border: solid 1px #ddd;
	}
</style>
